package org.gbif.portal.action;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.SessionAware;
import org.gbif.ecat.cfg.DataDirConfig;
import org.gbif.portal.model.Agent;

import com.google.inject.Inject;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

/**
 *
 */
public  class BaseAction extends ActionSupport implements Action, SessionAware{
	protected final Log log = LogFactory.getLog(getClass());
	public static final String NOT_FOUND   = "404";
	public static final String NOT_ALLOWED = "401";
	public static final String LOGIN_REQUIRED = "loginRequired";
	public static final String NOT_IMPLEMENTED = "notImplemented";
	@Inject protected Properties cfg;
	
	protected Map<String, Object> session;
	protected String currentMenu="index";

	public String execute(){
		return SUCCESS;
	}
	
	public String getDomain(){
		return cfg.getProperty("app.domain");
	}
	
	
	public String getCurrentMenu(){
		// is set via action constructor
		return currentMenu;
	}
	
	public Agent getUser(){
		Agent u=null;
		try {
			u=(Agent) session.get(DataDirConfig.SESSION_USER);
		} catch (Exception e) {
			//swallow. if session is not yet opened we get an exception here...
		}
		return u;
	}
	public boolean isLoggedIn(){
		return getUser()==null ? false : true;
	}
	public boolean getAdminUser(){
		return isAdminUser();
	}
	public boolean isAdminUser(){
		Agent u = getUser();
		if (u!=null && u.isAdmin()){
			return true;
		}
		return false;
	}

	protected List<String> splitMultiValueParameter(String value){
		if (value==null){
			return new ArrayList<String>();
		}
		String[] paras = StringUtils.split(value, ", ");
		return Arrays.asList(paras);
	}

	protected Map<String, String> translateI18nMap(Map<String, String> map){
		for (String key : map.keySet()){
			String i18Key = map.get(key);
			map.put(key, getText(i18Key));
		}
		return map;
	}

	public void setSession(Map<String, Object> session) {
		this.session= session;
	}

	public Properties getCfg() {
		return cfg;
	}
	public String getProperty(String key) {
		return cfg.getProperty(key);
	}
	
}
